﻿using Project.Yan.Net.BLL.DTOs;
using Project.Yan.Net.DAL;
using Project.Yan.Net.DAL.Entities;
using Project.Yan.Net.Redis.CacheModel;
using Project.Yan.Net.Redis.Helper;
using Project.Yan.Net.Tool.Ex;
using Project.Yan.Net.Tool.Mapster;

namespace Project.Yan.Net.BLL
{
    public class UserService
    {
        private readonly IUserRepository _userRepository;

        protected readonly UserCacheHelper _userCacheHelper;
        public UserService(IUserRepository userRepository, UserCacheHelper userCacheHelper)
        {
            _userRepository = userRepository;
            _userCacheHelper = userCacheHelper;
        }

        /// <summary>
        /// Get user by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<UserDTO> GetUser(int id)
        {
            var userEntity = await _userRepository.GetByIdAsync(id);
            if (userEntity == null)
            {
                throw new BusinessException("用户信息不能为空。", CodeEnums.其他);
            }
            return MapperHelper.Map<User, UserDTO>(userEntity);
        }
        /// <summary>
        /// Get user by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<UserDTO> GetUserCacheById(int id)
        {
            var userEntity = await _userCacheHelper.GetData(id);
            if (userEntity == null)
            {
                throw new BusinessException("用户信息不能为空。", CodeEnums.其他);
            }
            return MapperHelper.Map<UserCacheModel, UserDTO>(userEntity);
        }
        /// <summary>
        /// Get user by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<UserDTO> GetUserByEmail(string email)
        {
            var userEntity = await _userRepository.GetUserByEmailAsync(email);
            if (userEntity == null)
            {
                throw new BusinessException("用户信息不能为空。", CodeEnums.其他);
            }
            var userDto = MapperHelper.Map<User, UserDTO>(userEntity);
            return userDto;

        }

        /// <summary>
        /// Create user
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<UserDTO> CreateUser(UserCreateDTO request)
        {
            var userEntity = MapperHelper.Map<UserCreateDTO, User>(request);
            await _userRepository.AddAsync(userEntity);
            await _userRepository.SaveChangesAsync();
            var userDto = MapperHelper.Map<UserCreateDTO, UserDTO>(request);
            return userDto;
        }
    }
}
